package org.qydjk.console.controller.wechatPublicNumber;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.WechatPublicContent;
import org.qydjk.common.pojo.WechatPublicInteraction;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Lanan on 2017/12/25 0025.
 */
@Controller
@RequestMapping("/wechat/public/number")
public class WechatPublicNumberContentAndInteractionController extends BaseController {
    /**
     * 微信公众号交互与内容index
     * @return 字符串
     */
    @RequestMapping("/contentAndInteraction/index.do")
    public String wechatPublicNumberIndex() {
        return "wechatPublicNumber/contentAndInteraction/wechatPublicNumberContentAndInteraction";
    }


    /*--------------------------------------------------交互----------------------------------------------------*/
    /**
     * 公众号交互列表
     * @param page 当前页
     * @param rows 总页数
     * @return 返回结果
     */
    @RequestMapping("/interaction/list.do")
    @ResponseBody
    public Object wechatPublicNumberInteractionList(int page, int rows) {

        String sql = "SELECT * FROM qy_wechat_public_interaction WHERE 1 = 1";
        String countSql = "SELECT COUNT(id) FROM qy_wechat_public_interaction WHERE 1 = 1";

        sql += addInteractionWhereStr();
        countSql += addInteractionWhereStr();

        sql += " ORDER BY update_time DESC";

        return objetList(sql, countSql, page, rows, WechatPublicInteraction.class);
    }

    private String addInteractionWhereStr() {
        String where = "";
        where += addAndLikeStr("name", request.getParameter("name"));
        where += addAndLikeStr("k", request.getParameter("k"));
        where += addAndEqulStr("type", request.getParameter("type"));
        where += addAndEqulStr("reply_type", request.getParameter("replyType"));
        return where;
    }

    /**
     * 微信交互插入
     * @param wechatPublicInteraction 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/interaction/insert.do")
    @ResponseBody
    public Object wechatPublicNumberInteractionInsert(WechatPublicInteraction wechatPublicInteraction) {
        wechatPublicInteraction.setCreateTime(new Date());
        wechatPublicInteraction.setStatus(1);
        return handleSaveOrUpdateInteraction(true, wechatPublicInteraction);
    }

    /**
     * 微信交互修改
     * @param wechatPublicInteraction 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/interaction/update.do")
    @ResponseBody
    public Object wechatPublicNumberInteractionUpdate(WechatPublicInteraction wechatPublicInteraction) {
        return handleSaveOrUpdateInteraction(false, wechatPublicInteraction);
    }

    /**
     * 交互保存与修改处理
     * @param isSave
     * @param wechatPublicInteraction
     * @return
     */
    private Object handleSaveOrUpdateInteraction(Boolean isSave, WechatPublicInteraction wechatPublicInteraction) {
        Map<String, Object> map = handleInteractionK(isSave, wechatPublicInteraction);
        String isCanNext = map.get("isCanNext").toString();
        if (isCanNext.equals("false")) {
            JSONObject resp = new JSONObject();
            resp.put("success", false);
            resp.put("msg", map.get("msg").toString());
            return JSON.toJSON(resp);
        }
        wechatPublicInteraction.setUpdateTime(new Date());
        // 如果是添加
        if (isSave) {
            return handleSave(wechatPublicInteraction);
        }
        return handleInteractionUpdate(wechatPublicInteraction);
    }

    private Object handleInteractionUpdate(WechatPublicInteraction wechatPublicInteraction) {
        try {
            WechatPublicInteraction oldIn = baseService.get(WechatPublicInteraction.class, wechatPublicInteraction.getId());
            return handleUpdate(wechatPublicInteraction, oldIn);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resp = new JSONObject();
            resp.put("msg", e.toString());
            resp.put("success", false);
            return JSON.toJSON(resp);
        }
    }

    /**
     * 当添加时 数据库中已存在 活当修改时数据库中已存在另一个key一样
     * @param isSave
     * @param wechatPublicInteraction
     * @return 判断结果
     */
    private Map<String, Object> handleInteractionK(Boolean isSave, WechatPublicInteraction wechatPublicInteraction) {
        String k = wechatPublicInteraction.getK();
        Integer id = wechatPublicInteraction.getId();
        Map<String, Object> map = new HashMap<String, Object>();
        String sql = "SELECT * FROM qy_wechat_public_interaction WHERE k = '" + k + "'";
        try {
            List<WechatPublicInteraction> wechatPublicInteractions = baseService.findBySQL(sql, WechatPublicInteraction.class);
            if (wechatPublicInteractions.size() > 0) {
                WechatPublicInteraction oldIn = wechatPublicInteractions.get(0);
                if (id != null && id == oldIn.getId() && !isSave) {
                    map.put("isCanNext", "true");
                } else {
                    if (isSave) {
                        map.put("isCanNext", "false");
                        map.put("msg", "该微信交互关键字key已存在！添加失败");
                    } else {
                        map.put("isCanNext", "false");
                        map.put("msg", "该微信交互关键字key已存在！修改失败");
                    }
                }
            } else {
                map.put("isCanNext", "true");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isCanNext", "false");
            map.put("msg", "操作出错!");
        }
        return map;
    }

    /**
     * 微信交互删除
     * @param wechatPublicInteraction 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/interaction/delete.do")
    @ResponseBody
    public Object wechatPublicNumberInteractionList(WechatPublicInteraction wechatPublicInteraction) {
        JSONObject resp = new JSONObject();
        String sql = "SELECT COUNT(id) FROM qy_wechat_public_content WHERE wechat_public_interaction_id = " + wechatPublicInteraction.getId();
        try {
            Integer count = baseService.getRecordCountSQL(sql);
            if (count > 0) {
                resp.put("success", false);
                resp.put("msg", "该交互信息下存在交互内容,删除失败!");
            } else {
                return handelDelete(wechatPublicInteraction, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 启用和禁用处理 交互
     * @param id 操作项id
     * @param status 操作成的状态
     * @return 处理结果
     */
    @RequestMapping("/interaction/changeInteractionStatusToEnableOrDisable.do")
    @ResponseBody
    public Object changeInteractionStatusToEnableOrDisable(Integer id, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            WechatPublicInteraction wechatPublicInteraction = baseService.get(WechatPublicInteraction.class, id);
            wechatPublicInteraction.setStatus(status);
            wechatPublicInteraction.setUpdateTime(new Date());
            if (status == 0) {
                Date date = new Date();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sf.format(date);
                String sql = "UPDATE qy_wechat_public_content SET `status`='0', update_time = '" + dateStr + "' WHERE wechat_public_interaction_id = '" + id + "'";
                baseService.excuteSQL(sql);
            }
            baseService.saveOrUpdate(wechatPublicInteraction);
            resp.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }



    /*--------------------------------------------------交互内容----------------------------------------------------*/
    /**
     * 公众号交互内容列表
     * @param page 当前页
     * @param rows 总页数
     * @return 返回结果
     */
    @RequestMapping("/content/list.do")
    @ResponseBody
    public Object wechatPublicNumberContentList(int page, int rows) {
        String sql = "SELECT * FROM qy_wechat_public_content WHERE 1 = 1";
        String countSql = "SELECT COUNT(id) FROM qy_wechat_public_content WHERE 1 = 1";
        sql += addContentWhereStr();
        countSql += addContentWhereStr();
        sql += " ORDER BY ord DESC";
        return objetList(sql, countSql, page, rows, WechatPublicContent.class);
    }

    public String addContentWhereStr() {
        String whereStr = "";
        whereStr += addAndEqulStr("wechat_public_interaction_id", request.getParameter("contentId"));
        whereStr += addAndLikeStr("title", request.getParameter("title"));
        whereStr += addAndLikeStr("content", request.getParameter("content"));
        whereStr += addAndLikeStr("description", request.getParameter("description"));
        return whereStr;
    }

    /**
     * 微信交互内容插入页面
     * @return 页面地址
     */
    @RequestMapping("/content/insert/index.do")
    public Object wechatPublicNumberContentInsertIndex() {
        return "wechatPublicNumber/contentAndInteraction/wechatPublicNumberContentInsert";
    }
    /**
     * 微信交互内容插入
     * @param wechatPublicContent 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/content/insert.do")
    @ResponseBody
    public Object wechatPublicNumberContentInsert(WechatPublicContent wechatPublicContent) {
        wechatPublicContent.setCreateTime(new Date());
        wechatPublicContent.setStatus(0);
        return handleSaveOrUpdateContent(true, wechatPublicContent);
    }

    /**
     * 微信交互内容修改页面
     * @return 页面地址
     */
    @RequestMapping("/content/update/index.do")
    public Object wechatPublicNumberContentUpdateIndex() {
        Integer id = Integer.valueOf(request.getParameter("id"));
        try {
            WechatPublicContent wechatPublicContent = baseService.get(WechatPublicContent.class, id.intValue());
            Integer wechatPublicInteractionId = wechatPublicContent.getWechatPublicInteractionId();
            WechatPublicInteraction wechatPublicInteraction =  baseService.get(WechatPublicInteraction.class, wechatPublicInteractionId.intValue());
            Integer replyType = wechatPublicInteraction.getReplyType();
            switch (replyType) {
                // 纯文本
                case 0: {
                } break;
                // 单图
                case 1: {
                } break;
                // 单图文
                case 2: {
                } break;
                // 图文列表
                case 3: {
                    wechatPublicContent.setImg(wechatPublicContent.getPicUrl());
                    wechatPublicContent.setContent(wechatPublicContent.getDescription());
                } break;
            }
            request.setAttribute("content", wechatPublicContent);
            request.setAttribute("replyType", replyType);
            return "wechatPublicNumber/contentAndInteraction/wechatPublicNumberContentUpdate";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信交互内容修改
     * @param wechatPublicContent 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/content/update.do")
    @ResponseBody
    public Object wechatPublicNumberContentUpdate(WechatPublicContent wechatPublicContent) {
        return handleSaveOrUpdateContent(false, wechatPublicContent);
    }

    // 声明该全局变量用于保存处理交互内容
    private Integer replyType = 0;
    /**
     * 处理交互内容的更新与添加
     * @param isSave 是否是添加
     * @param wechatPublicContent 预处理信息
     * @return 处理结果
     */
    private Object handleSaveOrUpdateContent(Boolean isSave, WechatPublicContent wechatPublicContent) {
        JSONObject resp = new JSONObject();
        Map<String, Object> map = handleInteractionSubContentCount(wechatPublicContent, isSave);
        if ("true".equals(map.get("isCanNext").toString())) {
            wechatPublicContent.setUpdateTime(new Date());
            deleteAnotherForReplyType(wechatPublicContent);
            if (isSave) {
                return handleSave(wechatPublicContent);
            }
            try {
                WechatPublicContent oldWPC = baseService.get(WechatPublicContent.class, wechatPublicContent.getId().intValue());
                return handleUpdate(wechatPublicContent, oldWPC);
            } catch (Exception e) {
                e.printStackTrace();
                resp.put("msg", e.toString());
                resp.put("success", false);
            }
        } else {
            resp.put("msg", map.get("msg").toString());
            resp.put("success", false);
        }
        return JSON.toJSON(resp);
    }

    /**
     * 通过发送类型将多余的value清空
     * @param wechatPublicContent 预处理数据
     */
    private void deleteAnotherForReplyType(WechatPublicContent wechatPublicContent) {
        switch (replyType) {
            // 纯文本
            case 0: {
                wechatPublicContent.setDescription("");
                wechatPublicContent.setImg("");
                wechatPublicContent.setPicUrl("");
                wechatPublicContent.setUrl("");
                wechatPublicContent.setMediaId("");
            } break;
            // 单图
            case 1: {
                wechatPublicContent.setContent("");
                wechatPublicContent.setDescription("");
                wechatPublicContent.setPicUrl("");
                wechatPublicContent.setUrl("");
                wechatPublicContent.setImg("");
            } break;
            // 单图文
            case 2: {
                wechatPublicContent.setPicUrl("");
                wechatPublicContent.setDescription("");
                wechatPublicContent.setMediaId("");
            } break;
            // 图文列表
            case 3: {
                wechatPublicContent.setDescription(wechatPublicContent.getContent());
                wechatPublicContent.setContent("");
                wechatPublicContent.setPicUrl(wechatPublicContent.getImg());
                wechatPublicContent.setImg("");
                wechatPublicContent.setMediaId("");
            } break;
        }
    }

    /**
     * 处理当前选择的交互信息下交互内容是否超出限制
     * @param wechatPublicContent 预处理内容
     * @return 处理结果
     */
    private Map<String, Object> handleInteractionSubContentCount(WechatPublicContent wechatPublicContent, boolean isSave) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Integer wechatPublicInteractionId = wechatPublicContent.getWechatPublicInteractionId();
            WechatPublicInteraction wechatPublicInteraction = baseService.get(WechatPublicInteraction.class, wechatPublicInteractionId);
            replyType = wechatPublicInteraction.getReplyType();
            if (!isSave) {
                WechatPublicContent oldWPC = baseService.get(WechatPublicContent.class, wechatPublicContent.getId().intValue());
                if (oldWPC.getWechatPublicInteractionId() == wechatPublicContent.getWechatPublicInteractionId()) {
                    map.put("isCanNext", "true");
                    return map;
                }
            }
            String countSql = "SELECT COUNT(id) FROM qy_wechat_public_content WHERE wechat_public_interaction_id = '" + wechatPublicInteractionId + "'";
            Integer count = baseService.getRecordCountSQL(countSql);
            switch (replyType) {
                // 纯文本
                case 0: {
                    map = handleContentCanNext(1, count);
                } break;
                // 单图
                case 1: {
                    map = handleContentCanNext(1, count);
                } break;
                // 单图文
                case 2: {
                    map = handleContentCanNext(1, count);
                } break;
                // 图文列表
                case 3: {
                    map = handleContentCanNext(5, count);
                } break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("isCanNext", "false");
            map.put("msg", e.toString());
        }
        return map;
    }

    /**
     * 判断是否超过最大限制数 添加
     * @param maxContent 最大限制数
     * @param count 当前已有数量
     * @return 处理结果
     */
    private Map<String, Object> handleContentCanNext(Integer maxContent, Integer count) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (count >= maxContent) {
            map.put("isCanNext", "false");
            map.put("msg", "该交互信息下交互内容已超过最大限度!");
        } else {
            map.put("isCanNext", "true");
        }
        return map;
    }

    /**
     * 微信交互内容删除
     * @param wechatPublicContent 预处理信息
     * @return 处理结果
     */
    @RequestMapping("/content/delete.do")
    @ResponseBody
    public Object wechatPublicNumberContentList(WechatPublicContent wechatPublicContent) {
        JSONObject resp = new JSONObject();
        return handelDelete(wechatPublicContent, resp);
    }

    /**
     * 启用和禁用处理 交互内容
     * @param id 操作项id
     * @param status 操作成的状态
     * @return 处理结果
     */
    @RequestMapping("/content/changeContentStatusToEnableOrDisable.do")
    @ResponseBody
    public Object changeContentStatusToEnableOrDisable(String id, Integer status) {
        JSONObject resp = new JSONObject();
        try {
            String sql;
            Date date = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = sf.format(date);
            if (status == 1) {
                sql = "UPDATE qy_wechat_public_content wpc " +
                        "SET wpc.`status` = '1', wpc.update_time = '" + dateStr + "' " +
                        "WHERE wpc.`status` = '0' " +
                        "AND wpc.id IN (" + id + ") " +
                        "AND EXISTS " +
                        "(SELECT wpi.id " +
                        "FROM qy_wechat_public_interaction wpi " +
                        "WHERE wpc.wechat_public_interaction_id = wpi.id " +
                        "AND wpi.`status` = '1'" +
                        ")";
            } else {
                sql = "UPDATE qy_wechat_public_content wpc " +
                        "SET wpc.`status` = '0', wpc.update_time = '" + dateStr + "' " +
                        "WHERE wpc.`status` = '1' " +
                        "AND wpc.id IN (" + id + ") ";
            }
            baseService.excuteSQL(sql);
            resp.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    @RequestMapping("/content/getContentCombobox.do")
    @ResponseBody
    public Object getContentCombobox() {
        try {
            List<WechatPublicInteraction> wechatPublicInteractions = baseService.findByHql("from WechatPublicInteraction order by updateTime desc");
            return wechatPublicInteractions;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /*--------------------------------------------------公共管理----------------------------------------------------*/

    /**
     * 获取查询列表
     * @param sql 查询语句
     * @param countSql 个数语句
     * @param page 当前页
     * @param rows 总页
     * @param cls class
     * @return 查询结果
     */
    private Object objetList(String sql, String countSql, int page, int rows, Class<?> cls) {
        List<Object> objects = new ArrayList<Object>();
        Integer total = 0;
        try {
            objects = baseService.findBySQL(sql, cls, new HibernatePage(page, rows));
            total = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new EasyUIResponse(total, objects);
    }

    /**
     * 添加数据库"="条件语句
     * @param key 数据库字段名
     * @param value 查询的值
     * @return 返回处理结构钢字符串
     */
    public String addAndEqulStr(String key, String value) {
        if (StringUtil.isEmptyOrNull(value)) {
            return "";
        }
        return " AND " + key + " = " + value;
    }

    /**
     * 添加数据库"like"条件语句
     * @param key 数据库字段名
     * @param value 查询的值
     * @return 返回处理结构钢字符串
     */
    public String addAndLikeStr(String key, String value) {
        if (StringUtil.isEmptyOrNull(value)) {
            return "";
        }
        return " AND " + key + " like '%" + value + "%'";
    }

    /**
     * 将保存单独提出来
     * @param newObject
     * @return
     */
    private Object handleSave(Object newObject) {
        JSONObject resp = new JSONObject();
        try {
            baseService.save(newObject);
            resp.put("success", true);
            resp.put("msg", "添加");
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
            e.printStackTrace();
        }
        return JSON.toJSON(resp);
    }

    /**
     * 将修改单独提出来
     * @param newObject
     * @param oldObject
     * @return
     */
    private Object handleUpdate(Object newObject, Object oldObject) {
        JSONObject resp = new JSONObject();
        if (oldObject != null) {
            BeanUtil.copyProperties(newObject, oldObject);
            try {
                baseService.update(oldObject);
                resp.put("success", true);
                resp.put("msg", "修改");
            } catch (Exception e) {
                e.printStackTrace();
                resp.put("msg", e.toString());
                resp.put("success", false);
            }
        } else {
            resp.put("success", false);
            resp.put("msg", "修改失败");
        }
        return JSON.toJSON(resp);
    }

    private Object handelDelete(Object object, JSONObject resp) {
        try {
            resp.put("success", true);
            baseService.delete(object);
        } catch (Exception e) {
            resp.put("msg", e.toString());
            resp.put("success", false);
        }
        return JSON.toJSON(resp);
    }
}
